package net.qiujuer.tips.factory.presenter;

import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;
import net.qiujuer.tips.factory.cache.Cache;
import net.qiujuer.tips.factory.cache.notify.UpdateListNotify;
import net.qiujuer.tips.factory.model.adapter.HealthViewModel;
import net.qiujuer.tips.factory.model.db.HealthModel;
import net.qiujuer.tips.factory.view.HealthView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class HealthPresenter implements UpdateListNotify<HealthViewModel> {
    private HealthView mView;
    private int mtype;
    public HealthPresenter(HealthView view) {
        mView = view;

        Cache cache = Cache.getInstance();
        cache.cacheNotify.addUpdateHealthsNotify(this);

    }

    public void refresh(int type) {
        final HealthView view = mView;
        mtype = type;
        if (view == null)
            return;

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.setLoading(true);
            }
        });

        Cache cache = Cache.getInstance();
        update(cache.getHealths(type));
    }

    public void destroy() {
        mView = null;
        Cache cache = Cache.getInstance();
        cache.cacheNotify.removeUpdateHealthsNotify(this);
    }

    private void update() {
        HealthView view = mView;
        if (view == null)
            return;

        List<HealthViewModel> dataList = new ArrayList<HealthViewModel>();
        List<HealthModel> models = HealthModel.getAll();
        for (HealthModel model : models) {
            HealthViewModel data = new HealthViewModel();
            data.set(model);
            dataList.add(data);
        }

        Collections.sort(dataList);
        update(dataList);
    }

    @Override
    public void update(final List<HealthViewModel> caches) {
        final HealthView view = mView;
        if (view == null)
            return;
        List<HealthViewModel> healthdataList = new ArrayList<>();
        List<HealthModel> models = HealthModel.getAll();
        for (HealthModel model : models) {
            HealthViewModel data = new HealthViewModel();
            data.set(model);

            if(model.getHealthtype() == mtype){
                healthdataList.add(data);
            }
            if(model.getQuickvalue() != 0 && mtype == 3){
                healthdataList.add(data);
            }

            if(model.getPeriodvalue() != 0 && mtype == 0){
                healthdataList.add(data);
            }
        }
        view.setDataSet(healthdataList);

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.setNull(false);
                view.notifyDataSetChanged();
                view.setLoading(false);
            }
        });
    }

}
